<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="会话ID">
        <el-input v-model="searchForm.sessionId" placeholder="请输入会话ID" clearable />
      </el-form-item>
      <el-form-item label="模型类型">
        <el-select v-model="searchForm.modelType" placeholder="请选择模型类型" clearable>
          <el-option label="DeepSeek" value="DEEPSEEK" />
          <el-option label="Qwen" value="QWEN" />
          <el-option label="GLM" value="GLM" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="总对话数"
        :value="statistics.totalChats || 0"
        icon="ChatDotRound"
        type="primary"
        :trend="statistics.chatGrowth"
      />
      <StatCard
        title="今日对话"
        :value="statistics.todayChats || 0"
        icon="ChatDotRound"
        type="success"
      />
      <StatCard
        title="活跃用户"
        :value="statistics.activeUsers || 0"
        icon="UserFilled"
        type="warning"
      />
      <StatCard
        title="平均消息数"
        :value="statistics.avgMessages || 0"
        icon="Document"
        type="info"
      />
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- 对话趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">对话趋势</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="chatTrendChartRef"
              :options="chatTrendChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 模型使用分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">模型使用分布</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="modelDistributionChartRef"
              :options="modelDistributionChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 聊天历史表格 -->
    <Card title="聊天历史列表">
      <template #extra>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #modelType="{ row }">
          <el-tag :type="getModelTypeColor(row.modelType)">
            {{ getModelTypeLabel(row.modelType) }}
          </el-tag>
        </template>
        
        <template #messageCount="{ row }">
          <el-badge :value="row.messageCount" :max="99" type="primary" />
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
          <el-button type="primary" link @click="handleViewMessages(row)">
            <el-icon><Document /></el-icon>
            查看消息
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 聊天历史详情对话框 -->
    <CommonDialog
      v-model="detailVisible"
      title="聊天历史详情"
      width="800px"
      :show-footer="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会话ID">{{ detailData.sessionId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailData.username }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailData.userId }}</el-descriptions-item>
        <el-descriptions-item label="模型类型">
          <el-tag :type="getModelTypeColor(detailData.modelType)">
            {{ getModelTypeLabel(detailData.modelType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="消息数量">{{ detailData.messageCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 'ACTIVE' ? 'success' : 'info'">
            {{ detailData.status === 'ACTIVE' ? '活跃' : '已结束' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </CommonDialog>
    
    <!-- 聊天消息对话框 -->
    <CommonDialog
      v-model="messageVisible"
      title="聊天消息"
      width="1000px"
      :show-footer="false"
    >
      <div class="message-container">
        <div class="message-header">
          <div class="session-info">
            <span>会话ID: {{ currentSession.sessionId }}</span>
            <span>用户: {{ currentSession.username }}</span>
            <span>模型: {{ getModelTypeLabel(currentSession.modelType) }}</span>
          </div>
          <div class="message-actions">
            <el-button @click="refreshMessages" :loading="messageLoading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        
        <div class="message-content" ref="messageContentRef">
          <div v-if="messageLoading && messages.length === 0" class="message-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          
          <div v-else-if="messages.length === 0" class="message-empty">
            <el-empty description="暂无消息" />
          </div>
          
          <div v-else class="message-list">
            <div
              v-for="(message, index) in messages"
              :key="index"
              class="message-item"
              :class="{ 'user-message': message.role === 'USER', 'assistant-message': message.role === 'ASSISTANT' }"
            >
              <div class="message-avatar">
                <el-icon v-if="message.role === 'USER'"><UserFilled /></el-icon>
                <el-icon v-else><ChatDotRound /></el-icon>
              </div>
              <div class="message-body">
                <div class="message-role">
                  {{ message.role === 'USER' ? '用户' : 'AI助手' }}
                </div>
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ message.createTime }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getChatHistoryList, getChatHistoryDetail, getChatMessages, deleteChatHistory, batchDeleteChatHistory, getChatHistoryStatistics } from '@/api/chatHistory'
import { useTable } from '@/hooks/useTable'
import { useDialog } from '@/hooks/useDialog'
import { formatDate } from '@/utils'

// 表格列配置
const columns = [
  {
    type: 'selection',
    width: '55'
  },
  {
    prop: 'sessionId',
    label: '会话ID',
    minWidth: '180'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: '120'
  },
  {
    prop: 'modelType',
    label: '模型类型',
    width: '120',
    slot: 'modelType'
  },
  {
    prop: 'messageCount',
    label: '消息数量',
    width: '120',
    slot: 'messageCount'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'updateTime',
    label: '更新时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'action',
    label: '操作',
    width: '200',
    slot: 'action',
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  username: '',
  sessionId: '',
  modelType: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalChats: 0,
  todayChats: 0,
  activeUsers: 0,
  avgMessages: 0,
  chatGrowth: 0
})

// 图表相关
const chatTrendChartRef = ref(null)
const modelDistributionChartRef = ref(null)
const chartLoading = ref(false)
const chatTrendChartOptions = ref({})
const modelDistributionChartOptions = ref({})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  selectedRows,
  loadData,
  handleSelectionChange,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getChatHistoryList, {
  defaultParams: searchForm,
  immediate: false
})

// 对话框相关
const {
  visible: detailVisible,
  showDialog: showDetailDialog,
  hideDialog: hideDetailDialog
} = useDialog()

const {
  visible: messageVisible,
  showDialog: showMessageDialog,
  hideDialog: hideMessageDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const detailData = reactive({})
const currentSession = reactive({})
const messages = ref([])
const messageLoading = ref(false)
const messageContentRef = ref(null)

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getChatHistoryStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取图表数据
const getChartData = async () => {
  try {
    chartLoading.value = true
    
    // 模拟获取对话趋势数据
    const chatTrendData = {
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '对话数量',
          type: 'line',
          smooth: true,
          data: [120, 132, 101, 134, 90, 230, 210],
          areaStyle: {
            color: 'rgba(24, 144, 255, 0.2)'
          },
          lineStyle: {
            color: '#1890ff'
          }
        }
      ]
    }
    
    // 模拟获取模型分布数据
    const modelDistributionData = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '模型使用分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 335, name: 'DeepSeek' },
            { value: 310, name: 'Qwen' },
            { value: 234, name: 'GLM' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    chatTrendChartOptions.value = chatTrendData
    modelDistributionChartOptions.value = modelDistributionData
  } catch (error) {
    console.error('获取图表数据失败', error)
  } finally {
    chartLoading.value = false
  }
}

// 获取模型类型颜色
const getModelTypeColor = (modelType) => {
  const colors = {
    DEEPSEEK: 'primary',
    QWEN: 'success',
    GLM: 'warning'
  }
  return colors[modelType] || 'info'
}

// 获取模型类型标签
const getModelTypeLabel = (modelType) => {
  const labels = {
    DEEPSEEK: 'DeepSeek',
    QWEN: 'Qwen',
    GLM: 'GLM'
  }
  return labels[modelType] || modelType
}

// 处理搜索
const handleSearch = () => {
  loadData({
    ...searchForm,
    startTime: searchForm.dateRange?.[0],
    endTime: searchForm.dateRange?.[1]
  })
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    sessionId: '',
    modelType: '',
    dateRange: []
  })
  handleSearch()
}

// 处理查看
const handleView = async (row) => {
  try {
    const response = await getChatHistoryDetail(row.sessionId)
    if (response) {
      Object.assign(detailData, response)
      showDetailDialog()
    }
  } catch (error) {
    console.error('获取聊天历史详情失败', error)
  }
}

// 处理查看消息
const handleViewMessages = async (row) => {
  try {
    Object.assign(currentSession, row)
    messages.value = []
    showMessageDialog()
    await loadMessages(row.sessionId)
  } catch (error) {
    console.error('加载消息失败', error)
  }
}

// 加载消息
const loadMessages = async (sessionId) => {
  try {
    messageLoading.value = true
    const response = await getChatMessages(sessionId)
    if (response && response.data) {
      messages.value = response.data
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取消息失败', error)
  } finally {
    messageLoading.value = false
  }
}

// 刷新消息
const refreshMessages = async () => {
  await loadMessages(currentSession.sessionId)
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContentRef.value) {
    messageContentRef.value.scrollTop = messageContentRef.value.scrollHeight
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除会话 "${row.sessionId}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteChatHistory(row.sessionId)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的会话')
    return
  }
  
  const sessionIds = selectedRows.value.map(row => row.sessionId)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${sessionIds.length} 个会话吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteChatHistory(sessionIds)
      ElMessage.success('批量删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('批量删除失败', error)
    }
  }).catch(() => {})
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

onMounted(() => {
  loadData()
  getStatisticsData()
  getChartData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-base);
        box-shadow: var(--el-box-shadow-lighter);
        padding: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
        
        .chart-content {
          height: 300px;
        }
      }
    }
  }
  
  .message-container {
    display: flex;
    flex-direction: column;
    height: 600px;
    
    .message-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      .session-info {
        display: flex;
        gap: 16px;
        
        span {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
    
    .message-content {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      
      .message-loading {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        color: var(--el-text-color-secondary);
        
        .el-icon {
          font-size: 24px;
          margin-bottom: 8px;
        }
      }
      
      .message-empty {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      
      .message-list {
        .message-item {
          display: flex;
          margin-bottom: 16px;
          
          &.user-message {
            flex-direction: row-reverse;
            
            .message-avatar {
              margin-right: 0;
              margin-left: 12px;
            }
            
            .message-body {
              background-color: var(--el-color-primary-light-9);
              border-radius: 8px 0 8px 8px;
            }
          }
          
          &.assistant-message {
            .message-body {
              background-color: var(--el-fill-color-light);
              border-radius: 0 8px 8px 8px;
            }
          }
          
          .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--el-fill-color-lighter);
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 12px;
            flex-shrink: 0;
            
            .el-icon {
              font-size: 20px;
              color: var(--el-text-color-secondary);
            }
          }
          
          .message-body {
            max-width: 70%;
            padding: 12px;
            
            .message-role {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              margin-bottom: 4px;
            }
            
            .message-text {
              font-size: 14px;
              line-height: 1.5;
              color: var(--el-text-color-primary);
              margin-bottom: 8px;
              word-break: break-word;
            }
            
            .message-time {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              text-align: right;
            }
          }
        }
      }
    }
  }
}
</style>